<?php

namespace app\wap\controller;
use think\Controller;
use think\Request;
use app\common\controller\Common;

class Index extends Common
{
    public $param;
    public function _initialize(){
        parent::_initialize();

        // 初始化操作
        $local_sign = $this->getSign();
        // 不参与签名验证的方法
        if(!in_array(strtolower($this->a), array('customer_read','record'))) {
            if($local_sign != input('sign')) {
                exit(json_encode($this->returnData(1,'签名失败')));//签名失败
            }
            if(time() - input('time') > 60) {
                exit(json_encode($this->returnData(2,'请求超时')));//签名失败
            }
        }
        $this->param = Request::instance()->param();;
    }

    /**
     * crm获取员工列表API   ok
     *
     * @return array 返回类型
     * @example 示例 http://crm9.xibuts.cn/index.php/wap/index/index
     * @author Created by xing <lx@xibuts.cn>
     */
    public function index(){
        $userList = db('admin_user')
            ->where(['user.id' => ['gt',0]])
            ->alias('user')
            ->where('user.status>0 and user.type=1')
            ->join('__ADMIN_STRUCTURE__ structure', 'structure.id = user.structure_id', 'LEFT')
            ->field('user.id,user.mobile,user.email,user.sex,user.realname,user.thumb_img,structure.name as s_name')
            ->select();
        foreach ($userList as $k=>$v) {
            $userList[$k]['username'] = $v['realname'];
            $userList[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';
        }
        exit(json_encode($this->returnData(0,'请求成功',$userList)));
    }

    /**
     * 获取客户信息
     *
     * @param int $id 客户id
     * @return array 返回类型
     * @example 示例 http://crm9.xibuts.cn/index.php/wap/index/customer_read/id/3269
     * @author Created by xing <lx@xibuts.cn>
     */
    function customer_read(){
        $customerModel = model('crm/Customer');
        $data = $customerModel->getDataById($this->param['id']);
        if (!$data) {
            exit(json_encode($this->returnData(3,$customerModel->getError())));
        }
        exit(json_encode($this->returnData(0,'请求成功',$data)));
    }

    /**
     * 获取跟进记录
     *
     * @param int $types_id 客户id
     * @param int $page 页码
     * @param int $limit 每页数量
     * @return array 返回类型
     * @example 示例 http://crm9.xibuts.cn/index.php/wap/index/record/types_id/3269/page/1/limit/20
     * @author Created by xing <lx@xibuts.cn>
     */
    public function record(){
        $param = $this->param;
        $param['types'] = 'crm_customer';
        $by = 'record';
        $recordModel = model('admin/Record');
        $data = $recordModel->getDataList($param, $by);
        if (!$data) {
            exit(json_encode($this->returnData(4,$recordModel->getError())));
        }
        $customerModel = model('crm/Customer');
        $customer = $customerModel->getDataById($this->param['types_id']);
        $data['customer'] = $customer;
        exit(json_encode($this->returnData(0,'请求成功',$data)));
    }

    /**
     * 获得添加客户需要的字段
     *
     * @return array 返回类型
     * @example 示例 http://crm9.xibuts.cn/index.php/wap/index/getField
     * @author Created by xing <lx@xibuts.cn>
     */
    public function getField(){
        $fieldModel = model('admin/Field');
        $param['types']  = 'crm_customer';
        $param['module'] = 'crm';
        $param['controller'] = 'customer';
        $param['action'] = 'save';
        if(isset($this->param['crm_id'])){
            $crm_id = intval($this->param['crm_id']);
            $customerModel = model('crm/Customer');
            $customerData = $customerModel->getDataById($crm_id);
        }
        $dataInfo = [];
        $data = $fieldModel->field($param, $dataInfo) ? : [];

        if(!empty($data)){
            foreach ($data as $key=>$val){
                if(isset($customerData[$val['field']])){
                    $data[$key]['value'] = $customerData[$val['field']];
                }
            }
        }
        exit(json_encode($this->returnData(0,'请求成功',$data)));
    }

    /**
     * 添加客户
     *
     * @param 类型 $userid 客户添加后属于哪个人员
     * @return array 返回类型
     * @example 示例  http://crm9.xibuts.cn/index.php/wap/index/save
     * @author Created by xing <lx@xibuts.cn>
     */
    public function save(){
        $customerModel = model('crm/Customer');
        $param = $this->param;
        $param['create_user_id'] = $param['userid'];
        $param['owner_user_id']  = $param['userid'];
        $param['follow']  = '待跟进';
        if ($res = $customerModel->createData($param)) {
            exit(json_encode($this->returnData(0,'添加成功',$res)));
        }
        exit(json_encode($this->returnData(5,$customerModel->getError())));
    }

    /**
     * 编辑客户
     *
     * @param 类型 $userid 客户添加后属于哪个人员
     * @return array 返回类型
     * @example 示例  http://crm9.xibuts.cn/index.php/wap/index/updateDataById
     * @author Created by xing <lx@xibuts.cn>
     */
    public function updateDataById(){
        $customerModel = model('crm/Customer');
        $param = $this->param;
        unset($param['time']);
        if ($customerModel->updateDataById($param, $param['id'])) {
            exit(json_encode($this->returnData(0,'编辑成功')));
        } else {
            exit(json_encode($this->returnData(6,$customerModel->getError())));
        }
    }


    /**
     * app端请求签名
     * @return type
     * sign = 除time的所有参数按照键名对关联数组进行升序排序后拼接后MD5加密
     */
    protected function getSign(){
        header("Content-type:text/html;charset=utf-8");
        $api_key = 'e10adc3949ba59abbe56e057f20f883e';
        $data = input('param.');
        unset($data['time']);    // 删除这两个参数再来进行排序
        unset($data['sign']);    // 删除这两个参数再来进行排序
        ksort($data);
        $str = implode('', $data);
        $str = $str.input('time').$api_key;
        return md5($str);
    }

    /**
     * 数据统一返回
     * @author xing <fbiufo@vip.qq.com>
     */
    protected function returnData($code = 1,$msg = '',$data = ''){
        return array('code' => $code, 'msg' => $msg, 'time' => time(), 'data' => $data);
    }
}